package com.ygou.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

public class FileUDUtil {
	public static List<String> FILENAME=new ArrayList<String>();
	public static String UPLOADDIR = "filecontent/";
	public static String FILEPATH;
	/**
	 * 将上传的文件进行重命名
	 * 
	 * @author geloin
	 * @date 2012-3-29 下午3:39:53
	 * @param name
	 * @return
	 */
	private static String rename(String name) {

		Long now = Long.parseLong(new SimpleDateFormat("yyyyMMddHH").format(new Date()));
		Long random = (long) (Math.random() * now);
		String fileName = now + "" + random;

		if (name.indexOf(".") != -1) {
			fileName += name.substring(name.lastIndexOf("."));
		}

		return fileName;
	}

	/**
	 * 压缩后的文件名
	 * 
	 * @author geloin
	 * @date 2012-3-29 下午6:21:32
	 * @param name
	 * @return
	 */
	private static String zipName(String name) {
		String prefix = "";
		if (name.indexOf(".") != -1) {
			prefix = name.substring(0, name.lastIndexOf("."));
		} else {
			prefix = name;
		}
		return prefix + ".zip";
	}

	/**
	 * 上传文件
	 * 
	 * @author geloin
	 * @date 2012-5-5 下午12:25:47
	 * @param request
	 * @param params
	 * @param values
	 * @return
	 * @throws Exception
	 */
	public static int upload(HttpServletRequest request) {

		List<String> types =Arrays.asList("png","jpeg","jpg","gif");
		
		MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = mRequest.getFileMap();

		String uploadDir = request.getSession().getServletContext().getRealPath("/") + FileUDUtil.UPLOADDIR;
		File file = new File(uploadDir);
		
		if (!file.exists()) {
			file.mkdir();
		}

		String fileName = null;
		int i = 0;
		//清空文件名集合
		for (Iterator<Map.Entry<String, MultipartFile>> it = fileMap.entrySet().iterator(); it.hasNext(); i++) {

			Map.Entry<String, MultipartFile> entry = it.next();
			MultipartFile mFile = entry.getValue();

			fileName = mFile.getOriginalFilename();
			if(!types.contains(fileName.substring(fileName.lastIndexOf(".")+1))){
				return -2;
			}

			String storeName = rename(fileName);

			String noZipName = uploadDir + storeName;
			
			try {
				//将文件拷贝到指定位置
				OutputStream os=new BufferedOutputStream(new FileOutputStream(noZipName));
				FileCopyUtils.copy(mFile.getInputStream(),os);
				FileUDUtil.FILENAME.add(storeName);
				FileUDUtil.FILEPATH=noZipName;
			} catch (Exception e) {
				e.printStackTrace();
				return -1;
			}
		}
		return 0;
	}
	
	public static int uploads(HttpServletRequest request){
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(  
                request.getSession().getServletContext());  
		String uploadDir = request.getSession().getServletContext().getRealPath("/") + FileUDUtil.UPLOADDIR;
		
		File filev = new File(uploadDir);
		
		if (!filev.exists()) {
			filev.mkdir();
		}
		List<String> types =Arrays.asList("png","jpeg","jpg","gif");
		try {
			if (request instanceof MultipartHttpServletRequest) {  
	            // 将request变成多部分request  
	            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;  
	            Iterator<String> iter = multiRequest.getFileNames();  
	            // 检查form中是否有enctype="multipart/form-data"  
	            if (multipartResolver.isMultipart(request) && iter.hasNext()) {  
	                // 获取multiRequest 中所有的文件名  
	                while (iter.hasNext()) {  
	                    // 适配名字重复的文件  
	                    List<MultipartFile> fileRows = multiRequest  
	                            .getFiles(iter.next().toString());  
	                    if (fileRows != null && fileRows.size() != 0) {  
	                        for (MultipartFile file : fileRows) {  
	                            if (file != null && !file.isEmpty()) {
	                            	if(!types.contains(file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1))){
	                    				return -2;
	                    			}
	                            	String storeName = rename(file.getOriginalFilename());
	                            	OutputStream os = new BufferedOutputStream(new FileOutputStream(uploadDir + storeName));
	                				FileCopyUtils.copy(file.getInputStream(),os);
	                                FileUDUtil.FILENAME.add(storeName); 
	                            }  
	                        }  
	                    }  
	                }  
	            }  
	        }
		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		}
		return 0;
	}
	
	/**
	 * 下载
	 * 
	 * @author geloin
	 * @date 2012-5-5 下午12:25:39
	 * @param request
	 * @param response
	 * @param storeName
	 * @param contentType
	 * @param realName
	 * @throws Exception
	 */
	public static void download(HttpServletRequest request, HttpServletResponse response, String storeName,
			String contentType, String realName) throws Exception {
		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;

		String ctxPath = request.getSession().getServletContext().getRealPath("/") + FileUDUtil.UPLOADDIR;
		String downLoadPath = ctxPath + storeName;

		long fileLength = new File(downLoadPath).length();

		response.setContentType(contentType);
		response.setHeader("Content-disposition",
				"attachment; filename=" + new String(realName.getBytes("utf-8"), "ISO8859-1"));
		response.setHeader("Content-Length", String.valueOf(fileLength));

		bis = new BufferedInputStream(new FileInputStream(downLoadPath));
		bos = new BufferedOutputStream(response.getOutputStream());
		byte[] buff = new byte[2048];
		int bytesRead;
		while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
			bos.write(buff, 0, bytesRead);
		}
		bis.close();
		bos.close();
	}
}
